package com.module.overview.ui.cardHistoryDetails.provider

import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.utils.AppUtils.getString
import com.common.base.utils.JsonUtils
import com.common.base.utils.SpanUtils
import com.common.base.utils.ViewUtils
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserStress
import com.module.ble.repo.UserStressRepo
import com.module.ble.utils.AllCardTypeConfig
import com.module.ble.utils.common48DataConvertToAverage
import com.module.ble.utils.groupStressDataByStressAndTime
import com.module.ble.widget.CusPieChartView
import com.module.ble.widget.StressBarChart
import com.module.overview.R
import java.util.Calendar

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/7/10
 *
 * 描述：压力比例卡片
 *
 * 修订历史：完成度95%
 *
 */
class OvPressureRatioCardProvider(time:Long,
                                  override val itemViewType: Int = AllCardTypeConfig.TYPE_CARD_PRESSURE_RATIO,
                                  override val layoutId: Int = R.layout.overview_pressure_ratio_crad_provider
) : BaseItemProvider<HistoryDetailsModel>() {

    private var curTime = time

    private var chartView:CusPieChartView?= null

    private var tvPressureRelax: TextView? = null
    private var tvPressureNormal: TextView? = null
    private var tvPressureMedium: TextView? = null
    private var tvPressureHigh: TextView? = null
    private var tvPieChartValue: TextView? = null

    init {
    }

    override fun onViewHolderCreated(viewHolder: BaseViewHolder, viewType: Int) {
        chartView = viewHolder.getView(R.id.pieChartView)

        tvPressureRelax = viewHolder.getView(R.id.tvPressureRelax)
        tvPressureNormal = viewHolder.getView(R.id.tvPressureNormal)
        tvPressureMedium = viewHolder.getView(R.id.tvPressureMedium)
        tvPressureHigh = viewHolder.getView(R.id.tvPressureHigh)
        tvPieChartValue = viewHolder.getView(R.id.tvPieChartValue)

        super.onViewHolderCreated(viewHolder, viewType)
    }

    override fun convert(helper: BaseViewHolder, item: HistoryDetailsModel) {

        // 自定义圆环宽度
//        pieChartView.setStrokeWidth(30f)

        // 设置起始角度（从顶部开始）
        chartView?.setStartAngle(-90f)

//        // 设置背景圆环颜色
//        pieChartView.setBackgroundColor(Color.parseColor("#F0F0F0"))

        getTheDayStress()
    }


    /**
     * 获取当天压力
     */
    private fun getTheDayStress(){
        if (curTime <=0) return

        doOnIOThread {
            //当天压力
            UserStressRepo.instance.findByTimestampTheDay(curTime)?.let { originalListIt->
                //测试数据
////                val originalListIt :List<UserStress> = JsonUtils.fromJsonList("[{\"createdTime\":1755792060000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792060000,\"stress\":73},{\"createdTime\":1755792840000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792840000,\"stress\":80},{\"createdTime\":1755792900000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792900000,\"stress\":43},{\"createdTime\":1755792960000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755792960000,\"stress\":46},{\"createdTime\":1755796620000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755796620000,\"stress\":51},{\"createdTime\":1755796680000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755796680000,\"stress\":52},{\"createdTime\":1755797880000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755797880000,\"stress\":55},{\"createdTime\":1755798180000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798180000,\"stress\":86},{\"createdTime\":1755798060000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798060000,\"stress\":83},{\"createdTime\":1755798480000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798480000,\"stress\":90},{\"createdTime\":1755798600000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755798600000,\"stress\":98},{\"createdTime\":1755799200000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755799200000,\"stress\":30}]")
//                val originalListIt :List<UserStress> = JsonUtils.fromJsonList("[{\"createdTime\":1755878460000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755878460000,\"stress\":73},{\"createdTime\":1755879240000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755879240000,\"stress\":80},{\"createdTime\":1755879300000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755879300000,\"stress\":43},{\"createdTime\":1755879360000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755879360000,\"stress\":46},{\"createdTime\":1755883020000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755883020000,\"stress\":51},{\"createdTime\":1755883080000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755883080000,\"stress\":52},{\"createdTime\":1755884280000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755884280000,\"stress\":55},{\"createdTime\":1755886860000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755886860000,\"stress\":86},{\"createdTime\":1755888660000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755888660000,\"stress\":83},{\"createdTime\":1755892260000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755892260000,\"stress\":90},{\"createdTime\":1755892860000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755892860000,\"stress\":20},{\"createdTime\":1755924120000,\"endTime\":0,\"firmName\":\"2\",\"inDateTime\":1755924120000,\"stress\":52}]")
//
                if (originalListIt.isNullOrEmpty()) return@let
//                val listItStr = JsonUtils.toJson(originalListIt)

                val groupedSleepData = common48DataConvertToAverage(curTime, originalListIt)

                val theDayAverage = if (groupedSleepData.isNotEmpty()) {//当日平均
                    groupedSleepData.map { it.mValue }.average().toInt()
                } else {
                    60f
                }
//                val listItStr = JsonUtils.toJson(groupedSleepData)

                var mRelax = 0L//放松总时长
                var mNormal = 0L//正常总时长
                var mMedium = 0L//中等总时长
                var mHigh = 0L//偏高总时长


                groupedSleepData.forEach {
                    when(it.mValue.toInt()){
                        in 0..30 -> {//放松
                            mRelax+= 30
                        }
                        in 31..60 -> {//正常
                            mNormal+= 30
                        }
                        in 61..80 -> {//中等
                            mMedium+=30
                        }
                        in 81..100 -> {//偏高
                            mHigh+=30
                        }
                        else -> {// 处理超出范围的情况
                        }
                    }
                }
                // 计算总时长
                val totalTime = mRelax + mNormal + mMedium + mHigh

                // 计算各个状态占总时长的百分比
                val relaxProportion = if (totalTime > 0) (mRelax.toFloat() / totalTime * 100) else 0f
                val normalProportion = if (totalTime > 0) (mNormal.toFloat() / totalTime * 100) else 0f
                val mediumProportion = if (totalTime > 0) (mMedium.toFloat() / totalTime * 100) else 0f
                val highProportion = if (totalTime > 0) (mHigh.toFloat() / totalTime * 100) else 0f

                val chartData = listOf(
                    CusChartData(
                        createdTime = System.currentTimeMillis(),
                        mColor = ViewUtils.getColor(R.color.c_bcceff), // 浅蓝色
                        mProportion = relaxProportion // 放松总时长百分比%
                    ),
                    CusChartData(
                        createdTime = System.currentTimeMillis(),
                        mColor = ViewUtils.getColor(R.color.c_86b1ff), // 天蓝色
                        mProportion = normalProportion // 正常总时长百分比%
                    ),
                    CusChartData(
                        createdTime = System.currentTimeMillis(),
                        mColor = ViewUtils.getColor(R.color.c_5282ff), // 深蓝色
                        mProportion = mediumProportion //中等总时长百分比%
                    ),
                    CusChartData(
                        createdTime = System.currentTimeMillis(),
                        mColor = ViewUtils.getColor(R.color.c_ff8a06), // 橙色
                        mProportion = highProportion //偏高总时长百分比%
                    ),
                )

                doOnUiThread {
                    // 通知图表更新数据
                    chartView?.setData(chartData)
                    tvPressureRelax?.let {
                        SpanUtils.create()
                            .addSection("${getString(R.string.common_pressure_relax_hint)} ${relaxProportion.toInt()}${getString(R.string.common_bfb_unit)}")
                            .addForeColorSection("  ${TimeUtils.formatTime(mRelax*(1000 * 60), showHour = true, showMin = true)}",
                                ViewUtils.getColor(R.color.c_7f7f7f)
                            )
                            .showIn(it)
                    }
                    tvPressureNormal?.let {
                        SpanUtils.create()
                            .addSection("${getString(R.string.common_pressure_normal_hint)} ${normalProportion.toInt()}${getString(R.string.common_bfb_unit)}")
                            .addForeColorSection("  ${TimeUtils.formatTime(mNormal*(1000 * 60), showHour = true, showMin = true)}",
                                ViewUtils.getColor(R.color.c_7f7f7f)
                            )
                            .showIn(it)
                    }
                    tvPressureMedium?.let {
                        SpanUtils.create()
                            .addSection("${getString(R.string.common_pressure_medium_hint)} ${mediumProportion.toInt()}${getString(R.string.common_bfb_unit)}")
                            .addForeColorSection("  ${TimeUtils.formatTime(mMedium*(1000 * 60), showHour = true, showMin = true)}",
                                ViewUtils.getColor(R.color.c_7f7f7f)
                            )
                            .showIn(it)
                    }
                    tvPressureHigh?.let {
                        SpanUtils.create()
                            .addSection("${getString(R.string.common_pressure_high_hint)} ${highProportion.toInt()}${getString(R.string.common_bfb_unit)}")
                            .addForeColorSection("  ${TimeUtils.formatTime(mHigh*(1000 * 60), showHour = true, showMin = true)}",
                                ViewUtils.getColor(R.color.c_7f7f7f)
                            )
                            .showIn(it)
                    }

                    tvPieChartValue?.text = theDayAverage.toString()
                }
            }
        }
    }
}
